//
//  CZUserAccountViewModel.swift
//  SinaWeiBo
//
//  Created by 刘幼寒 on 5/20/16.
//  Copyright © 2016 刘幼寒. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject
{
    //单例
    static let sharedInstance: CZUserAccountViewModel = CZUserAccountViewModel()
    //归档和解档的路径
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    //账号，全局只要拿到单例就可以访问
    var userAccount: CZUserAccount?
    
    override init()
    {
        super.init()
        //加载沙盒里面的账号，赋值个userAccount,只需要加载一次
        self.userAccount = loadUserAccount()
    }
    
    
    func loadAccessToken(code: String, callBack: (error: NSError?) -> ())
    {
        //如果urlString里面开头是http或者HTTPS就直接使用这个urlString，如果不是以http或者HTTPS开头AFN会帮我们拼接baseURL
        let urlString = "oauth2/access_token"
        //参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        CZNetworkTool.sharedInstance.request(kREQUESTMETHOD.POST, URLString: urlString, parameters: parameters, progress: nil, success:
            { (task, responseObject) -> Void in
            
            //                    "access_token" = "2.00p7P_7GotgaDC0667ad0e67pdRQcB";
            //                    "expires_in" = 157679999;
            //                    "remind_in" = 157679999;
            //                    uid = 5885569283;
//                                    CZprint(items: "获得AcessToken成功：\(responseObject)")
            
            //将数据保存到模型当中去
                if let result = responseObject as? [String : AnyObject]
                {
                    //字典转模型
                    let userAccount = CZUserAccount(dict: result)
                    CZprint(items: userAccount)
                    //将模型归档到沙盒里面
                    NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.userAccountPath)
                    //将账号赋值给属性
                    self.userAccount = userAccount
                    
                    //保存账号密码成功后告诉控制器
                    callBack(error: nil)
                }
                else
                {
                    CZprint(items: "返回数据字典失败了")
                }
            
            }, failure: { (task, error) -> Void in
//                CZprint(items: "失败了：\(error)")
                //保存账号密码失败后告诉控制器错误原因
                callBack(error: error)
        })
        
    }
    
    //解档账号
    func loadUserAccount() -> CZUserAccount?
    {
        //解档对象
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? CZUserAccount
        {
            //加载到了账号,判断是否过期
            //userAccount.expiresDate() 和当前的时间比较
//            NSDate():当前时间
            //userAccount.expiresDate < NSDate() 过期的
            //测试：1.改系统时间2.该userAccount.expiresDate属性，早起的时间
//            userAccount.expiresDate = NSDate(timeIntervalSinceNow: -1000)
            if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending
            {
                //没有过期
                CZprint(items: "没有过期")
                return userAccount
            }
            else
            {
                return nil
            }
            
        }
        else
        {
            //没有加载出账号
            return nil
        }
       
    }
    

}
